package burp;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.Random;

public class UCManager {
	public String encryptHMac256(String content, String key) {
		String resultString = "";
		try {
			SecretKey secretKey = new SecretKeySpec(key.getBytes(),
					"HmacSHA256");

			Mac mac = Mac.getInstance(secretKey.getAlgorithm());

			mac.init(secretKey);

			byte[] digest = mac.doFinal(content.getBytes());
			resultString = new String(Base64.byteArrayToBase64(digest));
		} catch (Exception localException) {
		}
		return resultString;
	}

	private static String generateMixRandomCode(int sum) {
		String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < sum; i++) {
			int number = random.nextInt(62);

			sb.append(str.charAt(number));
		}
		return sb.toString();
	}

	public String getAuth(String id, String host, String method,
			String url, String macKey) {
		Date date = new Date();
		//String time = Long.toString(date.getTime());
		String nonce = date.getTime() + ":" + generateMixRandomCode(8);
		String content = nonce + "\n" + method + "\n" + url + "\n" + host + "\n";
		String s = this.encryptHMac256(content, macKey);
		String authorization = "MAC id=\"" + id + "\",nonce=\"" + nonce + "\",mac=\"" + s + "\""; 
		return authorization;
	}

	public static void main(String args[]) {
		UCManager u = new UCManager();
		
		String url = "POST /v0.9/tokens  HTTP/1.1\nHost: www.baidu.com\n";
		int i = url.indexOf("/");
		int x = url .indexOf("HTTP/1.1\n");
		String p = url.substring(i, x);
		//p = p.trim();
		System.out.println(i);
		System.out.println(x);
		System.out.println(p);
		int y = url.indexOf("Host:");
		String news = url.substring(0, y) + "Auth\n" + url.substring(y, url.length());
		System.out.println(news);
		System.out.println(u.getAuth("1CEA340F92EE6D382B8B152AC6F5466FD4FC9C64DE29E303A4BF136C82FA39DC6324F4C4CFA4DEEE", "101uccenter.dev.web.nd", "POST", "/v0.9/tokens", "jff51kp9jW"));
	}
}